package com.auxgroup.smarthome.job.peakvalley;

import com.auxgroup.smarthome.app.entity.AppPeakValleyRedisEntity;
import com.auxgroup.smarthome.constant.SmartElectricityConsant;
import com.auxgroup.smarthome.enterprise.service.DeviceManageService;
import com.auxgroup.smarthome.repo.AppPeakValleyRedisRepo;
import com.auxgroup.smarthome.utils.common.LOG;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by kevinchen on 2017/9/14.
 * 峰谷节电控制指令下发
 */
@Component
public class AppPeakValleyControlJob implements SimpleJob {

    @Autowired
    private AppPeakValleyRedisRepo appPeakValleyRedisRepo;
    @Autowired
    private DeviceManageService deviceManageService;


    /**
     * 峰谷节电控制指令下发
     * @param shardingContext
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        List<AppPeakValleyRedisEntity> peakValleyRedisEntities = appPeakValleyRedisRepo.getPartDataList(shardingContext.getShardingItem(), AppPeakValleyRedisEntity.class);
        StringBuilder logBuild = new StringBuilder();
        logBuild.append("任务名称：").append(shardingContext.getJobName()).append("--分片No:").append(shardingContext.getShardingItem()).append("--数据长度").append(peakValleyRedisEntities.size());
        LOG.info(this,logBuild.toString());
        peakValleyRedisEntities.stream().forEach(peakValleyRedisEntity->{
            // 用户是否已经关闭了峰谷节电，关闭峰谷节电的情况下无需再发送指令
            boolean closeState = peakValleyRedisEntity.isCloseState();
            // 巡检峰谷节电的状态
            boolean inspection = peakValleyRedisEntity.reachPeakStartHour() || peakValleyRedisEntity.reachValleyStartHour()
                    || peakValleyRedisEntity.closeTime();
            if (!closeState && inspection){
                int peakVallyStatus = 0; String oper = "关闭波峰波谷";
                if (peakValleyRedisEntity.reachValleyStartHour()){
                    peakVallyStatus =1; oper = "开启波谷";
                }
                if (peakValleyRedisEntity.reachPeakStartHour()){
                    peakVallyStatus = 2; oper = "开启波峰";
                }
                deviceManageService.controlPeakValleyAndSmartElectricity(peakValleyRedisEntity.getPk(),
                        peakValleyRedisEntity.getDid(),peakVallyStatus,0, SmartElectricityConsant.defaultElectricityValue);
                LOG.info(this,"波峰波谷控制指令: *******"+oper+"*********");
            }
        });
    }


}
